﻿using CDV.IRMS.WebAPI.TaskExecution.Utils;
using log4net;
using log4net.Config;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Reflection;

namespace CDV.IRMS.WebAPI.TaskExecution
{
    /// <summary>
    /// 任务执行WebApi服务入口类
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 入口方法
        /// </summary>
        /// <param name="args">启动参数</param>
        public static void Main(string[] args)
        {
            try
            {
                Console.Title = $"任务执行WebApi服务-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}";

                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                InitLog4net();

                _logger.Debug("********** 任务执行WebApi服务启动 **********");

                BuildWebHost(args).Run();
            }
            catch (Exception ex)
            {
                OutputLog($"********** 任务执行WebApi服务启动失败 ********** 异常信息如下：{ex}");
                Console.ReadLine();
            }
            finally
            {
                if (_logger != null)
                {
                    _logger.Debug("********** 任务执行WebApi服务停止 **********");
                }
            }
        }

        /// <summary>
        /// 构造WebHost
        /// </summary>
        /// <param name="args">启动参数</param>
        /// <returns>WebHost对象</returns>
        public static IWebHost BuildWebHost(string[] args)
        {
            //配置通过读取命令行参数获取监听URL
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddCommandLine(args)
                .Build();

            return WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(config)
                .UseKestrel()
                .UseStartup<Startup>()
                .Build();
        }

        /// <summary>
        /// 初始化Log4net
        /// </summary>
        private static void InitLog4net()
        {
            //创建Log4net仓储
            var repository = LogManager.CreateRepository(ServiceInjector.RepositoryName);
            //监控Log4net配置文件
            var log4netConfig = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "log4net.config");
            XmlConfigurator.ConfigureAndWatch(repository, new FileInfo(log4netConfig));

            _logger = LogManager.GetLogger(ServiceInjector.RepositoryName, ServiceInjector.LogName);
        }

        /// <summary>
        /// 处理未知异常
        /// </summary>
        /// <param name="sender">事件发生元对象</param>
        /// <param name="e">事件参数</param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            OutputLog($"任务执行服务发生未知错误，异常信息如下：{e.ExceptionObject}");
        }

        /// <summary>
        /// 输出错误信息
        /// </summary>
        /// <param name="errorMsg">错误信息</param>
        private static void OutputLog(string errorMsg)
        {
            if (_logger != null)
            {
                _logger.Error(errorMsg);
            }
            else
            {
                Console.WriteLine(errorMsg);
            }
        }

        /// <summary>
        /// Log对象
        /// </summary>
        private static ILog _logger;
    }
}
